package com.dongdong.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.dongdong.service.MsgService;
import com.google.gson.Gson;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.aliyun.teaopenapi.models.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class MsgServiceImpl implements MsgService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void sendPhoneMessage(String phoneNum) {
        String code = RandomStringUtils.randomNumeric(6);
        ValueOperations ops = redisTemplate.opsForValue();
        ops.set(phoneNum,code,1800, TimeUnit.SECONDS);
        Client client = null;
        try {
            client = createClient("LTAI4GCbdwnjCGwQj9Z3tr3N", "27ih4pc1W1tqey9X4mmCy1JUotAX7L");
        } catch (Exception e) {
            e.printStackTrace();

        }
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNum)
                .setSignName("东科创想").setTemplateCode("SMS_162522027")
                .setTemplateParam("{\"sms_code\":\""+code+"\"}");
        // 复制代码运行请自行打印 API 的返回值
        try {
            SendSmsResponse sms = client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public  Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
}
